package com.gph.saviorframework.security.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gph.saviorframework.Constants;
import com.gph.saviorframework.ErrorCode;
import com.gph.saviorframework.OaConstants;
import com.gph.saviorframework.SaviorFrameworkException;
import com.gph.saviorframework.common.model.Org;
import com.gph.saviorframework.common.model.Position;
import com.gph.saviorframework.common.model.User;
import com.gph.saviorframework.oa.model.UserExtInfo;
import com.gph.saviorframework.security.service.*;
import com.gph.saviorframework.security.web.editor.OrgEditor;
import com.gph.saviorframework.security.web.editor.PositionEditor;
import com.gph.saviorframework.uitl.ExcelParser;
import com.gph.saviorframework.uitl.ResourcePermissionUtils;
import com.gph.saviorframework.uitl.SecurityUtils;
import com.gph.saviorframework.util.RequestUtil;
import com.gph.saviorframework.util.SecUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by savior on 2016/3/24.
 * 用户控制器
 */
@Controller
@RequestMapping("/" + OaConstants.FRAMEWORK_REQUEST_PATH + "/user")
public class UserController {
    /**
     * 日志输出
     */
    final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 领域对象名称
     */
    private static final String domain = User.class.getSimpleName().toLowerCase();

    /**
     * 视图前缀
     */
    private static final String viewPrefix = OaConstants.FRAMEWORK_REQUEST_PATH + "/" + OaConstants.MODULE_CATEGORY_SECURITY + "/" + domain + "/"
            + domain + "_";


    /**
     * 用户数据服务
     */
    @Autowired
    private UserService userService;

   /* @Autowired
    private UserExtInfoService userExtInfoService;*/

    /**
     * 机构数据服务
     */
    @Autowired
    private OrgService orgService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private RoleService roleService;

    /**
     * 国际化资源
     */
    @Autowired
    private MessageSourceAccessor messages;

    @Autowired
    private SecurityUtils securityUtils;

    @Autowired
    private ResourcePermissionService resourcePermissionService;

    @Autowired
    private ResourcePermissionUtils resourcePermissionUtils;

    @Autowired
    private ExcelParser excelParser;

//    @Autowired
//    private UserOrclService userOrclService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Org.class, new OrgEditor(orgService));
        binder.registerCustomEditor(Position.class, new PositionEditor(positionService));
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String indexPage() throws SaviorFrameworkException {
        return viewPrefix + "index";
    }

    @RequestMapping(value = "/index", method = RequestMethod.POST)
    @ResponseBody
    public String list(
            @RequestParam(value = OaConstants.DEFAULT_PAGE_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_PAGE_START) Integer start,
            @RequestParam(value = OaConstants.DEFAULT_RECORD_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_PAGE_SIZE) Integer limit,
            @RequestParam(value = OaConstants.DEFAULT_SORT_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_SORT_FIELD) String sort,
            @RequestParam(value = OaConstants.DEFAULT_DIR_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_SORT_DIRECTION) String dir,
            @RequestParam(value = "org", required = false, defaultValue = "") String org,
            HttpServletRequest request)
            throws SaviorFrameworkException {
        String json = "";
        Map<String, Object> params = RequestUtil.getQueryMap(request, userService.getFields());
        try {
            Map<String, Object> map = userService.find(start, limit, sort, dir, params, org);
          //userExtInfo在海洋所系统中暂未用到先注释3.29
           /*  List<Map<String, Object>> list = (List<Map<String, Object>>) map.get(Constants.DEFAULT_RECORD_MODEL_KEY);
            Map<String, Object> result = null;
            for (Map<String, Object> record : list) {
                String username = record.get("username").toString();
               result = userExtInfoService.findById(username);
                if (result != null) {
                    record.putAll(result);
                }
            }*/
            json = JSONObject.toJSONString(map);
            logger.info(messages.getMessage("log.info.list", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain)}));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(messages.getMessage("log.error.list", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain)}));
        }
        return json;
    }

    @RequestMapping(value = "/index-fuzzy", method = RequestMethod.POST)
    @ResponseBody
    public String fuzzyList(
            @RequestParam(value = OaConstants.DEFAULT_PAGE_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_PAGE_START) Integer start,
            @RequestParam(value = OaConstants.DEFAULT_RECORD_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_PAGE_SIZE) Integer limit,
            @RequestParam(value = OaConstants.DEFAULT_SORT_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_SORT_FIELD) String sort,
            @RequestParam(value = OaConstants.DEFAULT_DIR_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_SORT_DIRECTION) String dir,
            @RequestParam(value = "org", required = false, defaultValue = "") String org,
            HttpServletRequest request)
            throws SaviorFrameworkException {
        String json = "";
        Map<String, Object> params = RequestUtil.getQueryMap(request, userService.getFields());
        try {
            Map<String, Object> map = userService.findFuzzy(start, limit, sort, dir, params, org);
            List<Map<String, Object>> list = (List<Map<String, Object>>) map.get(Constants.DEFAULT_RECORD_MODEL_KEY);
          /*  Map<String, Object> result = null;
            for (Map<String, Object> record : list) {
                String username = record.get("username").toString();
                result = userExtInfoService.findById(username);
                if (result != null) {
                    record.putAll(result);
                }
            }*/
            json = JSONObject.toJSONString(map);
            logger.info(messages.getMessage("log.info.list", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain)}));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(messages.getMessage("log.error.list", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain)}));
        }
        return json;
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createPage() throws SaviorFrameworkException {
        return viewPrefix + "create";
    }

    /**
     * 保存新建数据
     *
     * @param user 数据对象
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap create(@ModelAttribute User user,
                           @ModelAttribute UserExtInfo userExtInfo,
                           HttpServletRequest request) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            securityUtils.setCreateEntity(user);
            user.setPassword(SecUtils.getMD5(OaConstants.DEFAULT_PASSWORD.getBytes()));
            user.setVersion(OaConstants.VERSION_INIT_VALUE);
            userService.save(user);
//            userOrclService.save(user);
            //保存用户的扩展信息
            //userExtInfoService.save(userExtInfo);

            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
            modelMap.addAttribute(OaConstants.DEFAULT_ID_KEY, user.getUsername());
            logger.info(messages.getMessage("log.info.create", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain), user.getUsername()}));
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
            logger.error(messages.getMessage("log.error.create", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain)}));
        }
        return modelMap;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView editPage(@RequestParam(value = "id" , required = false) String username) throws SaviorFrameworkException {
        //return viewPrefix + "edit";
        ModelAndView modelAndView = new ModelAndView();
        if(null==username)
            username=securityUtils.getUser().getUsername();
        modelAndView.setViewName(viewPrefix + "edit");
        Map<String, Object> map = userService.findById(username);
        //用户扩展信息暂时未用到，注释掉3.29
        /*if (map != null) {
            Map<String, Object> result = userExtInfoService.findById(username);
            if (result != null) {
                map.putAll(result);
            }
        }
*/
        modelAndView.addObject("user", map);
        modelAndView.addObject("orgId", userService.get(username).getOrg().getId());

        return modelAndView;
    }

    @RequestMapping(value = "/edit/{username}", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap edit(@PathVariable("username") String username,
                         HttpServletRequest request) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            User user = userService.get(username);
            Position position = user.getPosition();
            Org org = user.getOrg();
            ServletRequestDataBinder binder = new ServletRequestDataBinder(user);
            initBinder(binder);
            binder.bind(request);
            securityUtils.setModifyEntity(user);// 设置修改数据的操作用户及时间信息
            if (!org.getId().equals(user.getOrg().getId())) {
                // 如果机构发生变化,则清除用户岗位和所有角色
                user.setPosition(null);
                userService.clearRole(username);
            } else if (!position.getId().equals(user.getPosition().getId())) {
                // 如果岗位发生变化,则清除用户所有角色
                userService.clearRole(username);
            }
            userService.update(user);
//            userOrclService.update(user);
            //保存或者更新用户的扩展信息
            //用户扩展信息暂时未用到，注释掉3.29
          /*  UserExtInfo userExtInfo = new UserExtInfo(username);
            binder = new ServletRequestDataBinder(userExtInfo);
            initBinder(binder);
            binder.bind(request);
            userExtInfoService.saveOrUpdate(userExtInfo);*/

            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
            logger.info(messages.getMessage("log.info.edit", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain), username}));
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, ErrorCode.UNCAUGHT_EXCEPTION);
            logger.error(messages.getMessage("log.error.edit",
                    new String[]{securityUtils.getUserFullName(), messages.getMessage(domain), username}));
        }
        return modelMap;
    }

    @RequestMapping(value = "/view/{username}", method = RequestMethod.GET)
    public
    @ResponseBody
    ModelMap get(@PathVariable("username") String username) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            Map<String, Object> map = userService.findById(username);
       /*     if (map != null) {
                Map<String, Object> result = userExtInfoService.findById(username);
                if (result != null) {
                    map.putAll(result);
                }
            }*/
            modelMap.addAttribute(OaConstants.DEFAULT_RECORD_MODEL_KEY, map);
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "/position", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getPosition(@RequestParam(value = "org", required = true) String org) throws SaviorFrameworkException {
        try {
            return positionService.findByOrg(org);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "/enable", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap enable(@RequestParam(value = "usernames", required = true) String[] usernames,HttpServletRequest httpServletRequest) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            Set<User> users = new HashSet<User>();
            User user = null;
            for (String username : usernames) {
                user = userService.get(username);
                if (user != null) {
                    user.setEnabled(true);
                    users.add(user);
                }
            }
            userService.update(users);
//            userOrclService.update(user);
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }

    /**
     * 用于新的启用——管理员点击页面启用按钮后，将用户角色改为PTYG，
     * 如果用户之前的角色为NEW_REGISTER需要发送短信
     * @param usernames
     * @param httpServletRequest
     * @return
     * @throws SaviorFrameworkException
     */
    @RequestMapping(value = "/enable2", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap enable2(@RequestParam(value = "usernames", required = true) String[] usernames,HttpServletRequest httpServletRequest) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            User user = null;
            for (String username : usernames) {
                user = userService.get(username);
                if (user != null) {
                  userService.clearRole(username);
                  userService.saveUserRole(new String[]{"PTYG"},username);
                }
            }

            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }
    @RequestMapping(value = "/disable", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap disable(@RequestParam(value = "usernames", required = true) String[] usernames) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            Set<User> users = new HashSet<User>();
            User user = null;
            for (String username : usernames) {
                user = userService.get(username);
                if (user != null) {
                    user.setEnabled(false);
                    users.add(user);
                }
            }
            userService.update(users);
//            userOrclService.update(user);
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "/resetpassword", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap resetPassword(@RequestParam(value = "usernames", required = true) String[] usernames) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            for (String username : usernames) {
                userService.resetPassword(username);
            }
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }

    /**
     * 修改密码
     *
     * @param oldPwd        老密码
     * @param newPwd        新密码
     * @param confirmNewPwd 确认新密码
     * @return
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap changePassword(
            @RequestParam(value = "oldPwd") String oldPwd,
            @RequestParam(value = "newPwd") String newPwd,
            @RequestParam(value = "confirmNewPwd") String confirmNewPwd,
            @RequestParam(value = "username") String userName,
            HttpServletRequest request) {
        ModelMap modelMap = new ModelMap();
        try {
            User user = userService.get(userName);
            if (user.getPassword().equals(SecUtils.getMD5(oldPwd.getBytes()))) {
                //如果旧密码和传过来的一致
                if (newPwd.equals(confirmNewPwd)) {
                    //修改密码
                    userService.resetPassword(userName, newPwd);
                    modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
                    String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/login";
                    SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
                    String currentDate=dft.format(new Date());
                } else {
                    modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
                }
            } else {
                modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, ex.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public
    @ResponseBody
    ModelMap delete(@RequestParam(value = "usernames", required = true) String[] usernames)
            throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            userService.deleteByIds(usernames);
          //  userExtInfoService.deleteByIds(usernames);
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
            logger.info(messages.getMessage("log.info.delete", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain),
                    StringUtils.arrayToDelimitedString((Object[]) usernames, "|")}));
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
            logger.error(messages.getMessage("log.error.delete", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain),
                    StringUtils.arrayToDelimitedString((Object[]) usernames, "|")}));
        }
        return modelMap;
    }

    /**
     * 返回分配角色页面
     *
     * @return 角色授权页面视图名称
     * @throws SaviorFrameworkException
     */
    @RequestMapping(value = "/role", method = RequestMethod.GET)
    public String assignRolePage() throws SaviorFrameworkException {
        return viewPrefix + "role_assign";
    }

    @RequestMapping(value = "/role/{user}", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap assignRole(@PathVariable("user") String user) {
        ModelMap modelMap = new ModelMap();
        try {
            modelMap.addAttribute(OaConstants.DEFAULT_RECORD_MODEL_KEY, roleService.findByUser(user));
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }

    /**
     * 保存用户与角色的关联信息.
     *
     * @param ids      角色id数组
     * @param username 用户名
     * @return
     */
    @RequestMapping(value = "/role", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap saveUserRole(@RequestParam(value = "ids", required = false) String[] ids, @RequestParam("username") String username) {
        ModelMap modelMap = new ModelMap();
        try {
            userService.saveUserRole(ids, username);
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "/select", method = RequestMethod.GET)
    public String userSelectPage() throws SaviorFrameworkException {
        return viewPrefix + "select";
    }

    @RequestMapping(value = "/select2", method = RequestMethod.GET)
    public String userSelect2Page() throws SaviorFrameworkException {
        return viewPrefix + "select2";
    }

    @RequestMapping(value = "/select-roles", method = RequestMethod.GET)
    public String userSelectByRolesPage() throws SaviorFrameworkException {
        return viewPrefix + "select_roles";
    }

    @RequestMapping(value = "/select-permission", method = RequestMethod.GET)
    public String userSelectByPermissionPage() throws SaviorFrameworkException {
        return viewPrefix + "permission_select";
    }

    @RequestMapping(value = "/index-permission", method = RequestMethod.POST)
    @ResponseBody
    public String listByPermission(@RequestParam(value = "dataType") String dataType,
                                   @RequestParam(value = OaConstants.DEFAULT_PAGE_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_PAGE_START) Integer start,
                                   @RequestParam(value = OaConstants.DEFAULT_RECORD_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_PAGE_SIZE) Integer limit,
                                   HttpServletRequest request)
            throws SaviorFrameworkException {
        String json = "";
        Map<String, Object> params = RequestUtil.getQueryMap(request, userService.getFields());
        try {
            List<String> userIds = resourcePermissionUtils.getUserIdsByResourcePermission(securityUtils.getUser().getUsername(), dataType);
            Map<String, Object> map = userService.findByPermission1(start,limit,userIds, params);
            json = JSONObject.toJSONString(map);
            logger.info(messages.getMessage("log.info.list", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain)}));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(messages.getMessage("log.error.list", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain)}));
        }
        return json;
    }

    @RequestMapping(value = "/index-roles", method = RequestMethod.POST)
    @ResponseBody
    public String listByRoles(@RequestParam(value = OaConstants.DEFAULT_PAGE_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_PAGE_START) Integer start,
                              @RequestParam(value = OaConstants.DEFAULT_RECORD_MODEL_KEY, required = false, defaultValue = OaConstants.DEFAULT_PAGE_SIZE) Integer limit,
                              @RequestParam(value = "rolesIds")List<String> rolesIds,
                              HttpServletRequest request)
            throws SaviorFrameworkException {
        String json = "";
        try {
            Map<String, Object> map = userService.findByRoles(start, limit, rolesIds);
            json = JSONObject.toJSONString(map);
            logger.info(messages.getMessage("log.info.list", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain)}));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(messages.getMessage("log.error.list", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain)}));
        }
        return json;
    }

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    @ResponseBody
    public void getUsersTree(HttpServletRequest request, HttpServletResponse response) throws SaviorFrameworkException, IOException {
        JSONArray array = new JSONArray();
        String id = request.getParameter("id");
        if (org.apache.commons.lang.StringUtils.isEmpty(id)) {
            id = securityUtils.getUser().getOrg().getId();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", securityUtils.getUser().getOrg().getId());
            map.put("name", securityUtils.getUser().getOrg().getName());
            map.put("pId", null);
            map.put("pName", null);
            map.put("nocheck", true);

            //构造子节点，包括用户和下级部门
            map.put("children", genOrgDataForZTree(id));

            array.add(map);
        } else {
            List<Map<String, Object>> list = genOrgDataForZTree(id);
            array = JSONArray.parseArray(JSONArray.toJSONString(list));
        }
        response.getWriter().write(array.toString());
    }

    private List<Map<String, Object>> genOrgDataForZTree(String orgId) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        List<Map<String, Object>> orgChildren = orgService.findByParent(orgId);
        for (Map<String, Object> temp : orgChildren) {
            temp.put("nocheck", true);
            temp.put("isParent", true);
        }
        list.addAll(orgChildren);

        List<User> users = userService.findByOrgId(orgId);
        //然后组织符合zTree的数据
        for (User user : users) {
            Map<String, Object> userMap = new LinkedHashMap<String, Object>();
            userMap.put("id", user.getUsername());
            userMap.put("name", user.getName());
            userMap.put("pId", orgId);
            userMap.put("pName", orgService.get(orgId).getId());

            list.add(userMap);
        }

        return list;
    }

    @RequestMapping(value = "/import", method = RequestMethod.GET)
    public String userImportPage() throws SaviorFrameworkException {
        return viewPrefix + "import";
    }

    @RequestMapping(value = "/importStaff", method = RequestMethod.GET)
    public String userStaffImportPage() throws SaviorFrameworkException {
        return viewPrefix + "import_staff";
    }
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap userImportMethod(@RequestParam("ucFile")MultipartFile ucFile,
                                     @RequestParam(value = "orgId")String orgId,
                                     @RequestParam(value = "positionId",required = false)String positionId) throws SaviorFrameworkException {

        ModelMap modelMap = new ModelMap();

        try{
            //todo:判断文件类型

            excelParser.parseUserExcelFile(ucFile.getInputStream(),orgId,positionId);//岗位编号暂定为2
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
        }
        catch (Exception ex){
            ex.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, ex.getMessage());
        }

        return modelMap;
    }

    /**
     * 导入登船人员信息
     * @param ucFile
     * @param vesselId
     * @return
     * @throws SaviorFrameworkException
     */
    @RequestMapping(value = "/importStaff", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap userImportMethod(@RequestParam("ucFile")MultipartFile ucFile,
                                     @RequestParam(value = "vesselId")String vesselId,  HttpServletRequest request) throws SaviorFrameworkException {

        ModelMap modelMap = new ModelMap();

        try{
            //todo:判断文件类型

            String message=excelParser.parseUserStaffExcelFile(request,ucFile.getInputStream(),vesselId);//岗位编号暂定为2
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
            modelMap.addAttribute("Message",message);
        }
        catch (Exception ex){
            ex.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, ex.getMessage());
        }

        return modelMap;
    }


    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register() throws SaviorFrameworkException {
        return viewPrefix + "rigister";
    }

    /**
     * 前台用户注册
     *
     * @param user 数据对象
     * @return
     */
    @RequestMapping(value = "/userRegister", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap userRegister(@ModelAttribute User user,
                           @ModelAttribute UserExtInfo userExtInfo,
                           HttpServletRequest request) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            Date date=new Date();
            user.setCreated(date);
            user.setModified(date);
            user.setUsername(user.getCertificateNum());//设置用户id为证件号
            user.setEnabled(true);
            user.setUserType("USER");//设置为普通用户
            user.setPosition(new Position("2"));//默认岗位，为了兼容框架
            user.setOrg(new Org("1000"));//默认部门，为了兼容已有框架
            user.setPassword(SecUtils.getMD5(Constants.DEFAULT_PASSWORD.getBytes()));
          /*  else{
                int length=user.getCertificateNum().length();
             user.setPassword(SecUtils.getMD5((user.getCertificateNum().substring(length-6)).getBytes()));
            }*/
            user.setVersion(OaConstants.VERSION_INIT_VALUE);
            user.setOrder(0);
            if(userService.existEmail(user.getEmail()))
            {
                modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
                modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY,"邮箱已被注册");
            }
            else if(null!=userService.findByCertificateNum(user.getCertificateNum())){
                modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
                modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY,"证件号已被注册");
            }else{
                userService.save(user);
//                userOrclService.save(user);
                //保存用户的扩展信息-暂未用到
               // userExtInfoService.save(userExtInfo);
                userService.saveUserRole(new String[]{"NEW_REGISTER"},user.getUsername());
                String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/login";

                modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
                modelMap.addAttribute(OaConstants.DEFAULT_ID_KEY, user.getUsername());
                logger.info(messages.getMessage("log.info.create", new String[]{user.getUsername(), messages.getMessage(domain), user.getUsername()}));
            }

        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(OaConstants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(OaConstants.DEFAULT_ERROR_KEY, e.getMessage());
            //logger.error(messages.getMessage("log.error.create", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain)}));
        }
        return modelMap;
    }
    @RequestMapping(value = "/registerSuccess", method = RequestMethod.GET)
    public String registerSuccess() throws SaviorFrameworkException {
        return viewPrefix + "newcount";
    }

}
